#include <iostream>
#include <fstream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>

#define PORT 5001
#define BUFFER_SIZE 4096

void send_file(const std::string &server_ip, const std::string &filename) {
	int client_socket = socket(AF_INET, SOCK_STREAM, 0);
	if (client_socket == -1) {
		std::cerr << "无法创建socket\n";
		return;
	}

	sockaddr_in server_addr = {};
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(PORT);
	inet_pton(AF_INET, server_ip.c_str(), &server_addr.sin_addr);

	if (connect(client_socket, (sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
		std::cerr << "连接失败\n";
		close(client_socket);
		return;
	}

	std::ifstream infile(filename, std::ios::binary | std::ios::ate);
	if (!infile.is_open()) {
		std::cerr << "无法打开文件: " << filename << "\n";
		close(client_socket);
		return;
	}
	long filesize = infile.tellg();
	infile.seekg(0, std::ios::beg);

	std::string file_info = filename + "," + std::to_string(filesize);
	send(client_socket, file_info.c_str(), file_info.size(), 0);

	char buffer[BUFFER_SIZE];
	long bytes_sent = 0;
	while (!infile.eof()) {
		infile.read(buffer, BUFFER_SIZE);
		ssize_t bytes_read = infile.gcount();
		send(client_socket, buffer, bytes_read, 0);
		bytes_sent += bytes_read;
		std::cout << "发送中... " << (100.0 * bytes_sent / filesize) << "%\n";
	}

	std::cout << "文件发送完成\n";
	infile.close();
	close(client_socket);
}

int main() {
	std::string server_ip = "10.250.5.103"; // 替换为实际的服务器IP地址
	std::string filename = "example.txt"; // 替换为要发送的文件路径

	send_file(server_ip, filename);
	return 0;
}
